//
//  ComposeViewController.swift
//  Microblog
//
//  Created by steaest on 15/8/11.
//  Copyright © 2015年 steaest. All rights reserved.
//

import UIKit

class ComposeViewController: UIViewController {
    
    
    //MARK: - 关闭
    func close() {
    
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK: - 发送微博
    func sendStatus() {
    
        print("发布微博")
    }
    
    func inputEmoticon() {
        print("选择表情")
    }
    
    //MARK: - 搭建界面
    override func loadView() {
        view = UIView()
        //试图控制器一定要设置背景颜色
        //如果发现动画切换视图控制器变慢,或者闪烁,重点检查是是否设置了背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        preparNav()
        preparTextView()
        preparToolbar()
    }
    
    //MARK: - 注意：此时的视图没有大小，不要在 viewDidLoad 中以及之前使用 view 作为参数设置控件位置
    override func viewDidLoad() {
        super.viewDidLoad()
        addkeyboardObserver()
        
    }
    deinit {
        removeKeyboardObserver()
    }
    
    //MARK: - 第一时间弹出键盘
    override func viewDidAppear(animated: Bool) {
        textView.becomeFirstResponder()
    }
    
    //添加键盘通知
    private func addkeyboardObserver() {
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //删除键盘通知
    private func removeKeyboardObserver() {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //toolbar的底部约束
    private var toolbarBottomCons: NSLayoutConstraint?
    
    //键盘变化监听方法,室友通知中心听到之后,由运行循环来调度执行,不能设置 private 的
    func keyboardChanged(n: NSNotification) {
        print(n)
        //获取目标 frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        //设置约束
        toolbarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
        
        //动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: - 准备文本框
    private func preparTextView() {
    
        view.addSubview(textView)
        //textView.backgroundColor = UIColor.orangeColor()
        
        print("文本框 + \(automaticallyAdjustsScrollViewInsets)")
        
        //自动布局
        //提示: 在iOS开发中,如果是单纯的 nav + scrollView 会自动调整滚动视图的边距
        //会将顶部的导航栏的高度预留出来,就能实现滚动视图穿透效果
        textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)

        placeholderLabel.text = "分享新鲜事"
        placeholderLabel.sizeToFit()
        textView.addSubview(placeholderLabel)
        placeholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
    //MARK: - 准备 toolbar
    private func preparToolbar() {
        //1. 创建toolbar
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        view.addSubview(toolbar)
        //设置布局
        //toolbar.translatesAutoresizingMaskIntoConstraints = false
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        //定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))
            
            //追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //删除最后一个 item
        items.removeLast()
        
        //设置 toolbar 的 items
        toolbar.items = items
    }
    
    //MARK: - 准备导航栏
    private func preparNav() {
        //1.左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
        
        //2.标题栏
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 35))
        
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text = UserAccount.sharedAccount?.name ?? ""
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }
    
    //MARK: - 懒加载控件
    //文本视图
    private lazy var textView: UITextView = {
        
        let tv = UITextView()
        
        tv.font = UIFont.systemFontOfSize(18)
//        tv.text = "分享新鲜事"
        
        //允许垂直拖拽
        tv.alwaysBounceVertical = true
        //拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
        }()
    //占位标签
    private lazy var placeholderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 18)
    //工具栏
    private lazy var toolbar = UIToolbar()
}
















